<?php
/**
 * Created by PhpStorm.
 * User: WD-QD-PHP-DEV-YU
 * Date: 2017/5/2
 * Time: 10:21
 */
namespace app\modules\admin\controllers;
use yii\web\Controller;
use Yii;
use app\models\SignupForm;
use app\models\User;
use yii\data\Pagination;

class UserAdminController extends Controller
{

    public function actionIndex(){

        $query = User::find()->where(['status'=>User::STATUS_ACTIVE]);

        $pages = new Pagination([
            'pageSize'=> 10,
            'totalCount'=> $query->count(),
        ]);

        $model = $query->offset($pages->offset)->limit($pages->limit)->all();

        return $this->render('index',[
            'model'=>$model,
            'pages'=>$pages,
        ]);
    }

    public function actionSignup(){
        $model = new SignupForm();

        if($model->load(Yii::$app->request->post()) && $model->signUp()){
            Yii::$app->session->setFlash('success','注册成功');
            return $this->redirect(['/admin/user-admin/index']);
        }

        return $this->render('signup',[
            'model' => $model
        ]);
    }

    public function actionDelete(){
        $uid = Yii::$app->request->post('uid');
        $user = User::findOne($uid);
       if(empty($user)){
           $return = ['status'=>0,'msg'=>'用户不存在'];
       }else{
           $user->status = User::STATUS_DELETED;
           $user->save();
           \Yii::$app->session->setFlash('success', '操作成功');
           $return = ['status'=>1,'msg'=>''];
       }

       Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        return $return;
    }

    public function actionChangePassword(){
        $uid = Yii::$app->request->post('uid');
        $new_password = Yii::$app->request->post('password');
        $user = User::findOne($uid);
        if(empty($user)){
            $return = ['status'=>0,'msg'=>'用户不存在'];
        }else{
            $user->setPassword($new_password);
            $user->save(false);
            \Yii::$app->session->setFlash('success', '操作成功');
            $return = ['status'=>1,'msg'=>''];
        }

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        return $return;
    }
}
